package openjdk.jdk.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by boot on 1/15/16.
 * <p>
 * Java NIO的通道类似流，但又有些不同：
 * 既可以从通道中读取数据，又可以写数据到通道。但流的读写通常是单向的。
 * 通道可以异步地读写。
 * 通道中的数据总是要先读到一个Buffer，或者总是要从一个Buffer中写入。
 */
public class TestFileChannel {
    public static void main(String[] args) throws IOException {
        try (RandomAccessFile raf = new RandomAccessFile("read.txt", "rw")) {
            FileChannel fc = raf.getChannel();
            // create a buffer with capacity with 48 bytes
            ByteBuffer buf = ByteBuffer.allocate(48);
            int bytesRead = fc.read(buf);   // read into buffer
            while (bytesRead != -1) {
                System.out.println("Read bytes :" + bytesRead);
                buf.flip();     // make sure ready to read
                while (buf.hasRemaining()) {
                    System.out.println((char) buf.get()); // read 1 byte one time
                }
                buf.clear();    // make sure read to write
                bytesRead = fc.read(buf);
            }
            //raf.close();
        }
    }
}
